<template>
<div>
  <el-card header="食品分类" shadow="always">
    <el-form :model="food" label-position="right" label-width="80px">
      <el-form-item label="食品分类">
        <el-select v-model="food.category_id">
          <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
        <el-button style="margin-left: 10px" type="success" @click="categoryForm=!categoryForm">新分类</el-button>
      </el-form-item>
      <template v-if="categoryForm">
        <el-form-item label="分类名称">
          <el-input v-model="food.category.name" placeholder="请输入分类名称"></el-input>
        </el-form-item>
        <el-form-item label="分类描述">
          <el-input v-model="food.category.description" placeholder="请输入分类描述"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="saveCategory">添加分类</el-button>
        </el-form-item>
      </template>
    </el-form>
  </el-card>
  <el-card header="食品信息" shadow="always">
    <el-form :model="food" label-width="80px" label-position="right">
      <el-form-item label="食品名称">
        <el-input v-model="food.name" placeholder="请输入食品名称"></el-input>
      </el-form-item>
      <el-form-item label="参加活动" v-if="!food.id">
        <el-input v-model="food.activity" placeholder="请输入活动内容"></el-input>
      </el-form-item>
      <el-form-item label="食品描述">
        <el-input v-model="food.descript" placeholder="请输入食品描述" type="textarea" show-word-limit maxlength="50" resize="none"></el-input>
      </el-form-item>
      <el-form-item label="食品图片">
        <el-upload :action="uploadPath" :before-upload="beforeUpload" :on-success="uploadSuccess" :headers="uploadHeader" :show-file-list="false">
          <el-button type="success">上传图片</el-button>
        </el-upload>
        <el-image v-if="image.showImage" :src="image.src" style="width: 100px;height: 100px" :preview-src-list="image.prevList"></el-image>
      </el-form-item>
      <el-form-item label="食品特色" v-if="!food.id">
        <el-select v-model="food.attributesJson" multiple>
          <el-option v-for="(item,index) in attrList" :key="index" :label="item.text" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="食物规格">
        <el-button type="success" @click="visible=true">添加规格</el-button>
        <el-table :data="food.specsJson" border>
          <el-table-column label="规格名称" prop="specs"/>
          <el-table-column label="打包费" prop="packing_fee"/>
          <el-table-column label="食物价格" prop="price"/>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="primary" size="small" @click="showSpecs(scope)">修改</el-button>
              <el-button type="danger" v-if="food.specsJson.length>1" @click="delSpecs(scope.$index)" size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="saveFood">保存</el-button>
      </el-form-item>
    </el-form>
    <el-dialog :title="title" :visible.sync="visible">
      <el-form :model="specs" label-width="80px" label-position="right">
        <el-form-item label="规格名称">
          <el-input v-model="specs.specs" placeholder="请输入规格名"></el-input>
        </el-form-item>
        <el-form-item label="打包费">
          <el-input-number v-model="specs.packing_fee"></el-input-number>
        </el-form-item>
        <el-form-item label="价格">
          <el-input-number v-model="specs.price"></el-input-number>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="saveSpecs">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </el-card>
</div>
</template>
<script>
const initInfo = {
  id: '',
  idShop: '',
  category_id: '',
  category: {
    name: '',
    description: ''
  },
  name: '',
  activity: '',
  descript: '',
  image_path: '',
  attributesJson: [],
  specsJson: [{ specs: '默认', packing_fee: 1, price: 10 }]
}
const initSpecs = {
  index: -1,
  specs: '默认',
  packing_fee: 1,
  price: 10
}
export default {
  name: 'Food',
  data () {
    return {
      food: { ...initInfo },
      categoryList: [],
      categoryForm: false,
      uploadPath: process.env.VUE_APP_BASE_API + 'file',
      uploadHeader: {
        Authorization: ''
      },
      image: {
        showImage: false,
        url: '',
        prevList: []
      },
      attrList: [
        {
          text: '新品',
          value: '新'
        }, {
          text: '招牌',
          value: '招牌'
        }
      ],
      specs: { ...initSpecs },
      title: '添加规格',
      visible: false
    }
  },
  methods: {
    /* 获取食品分类列表 */
    getCategoryList () {
      this.$http.get(`/shopping/getcategory/${this.food.idShop}`).then(({ data }) => {
        if (data.code === 20000) {
          this.categoryList = data.category_list
        }
      })
    },
    /* 保存食物分类 */
    saveCategory () {
      const category = this.food.category
      category.restaurant_id = this.food.idShop
      this.$http.post('/shopping/addcategory', category).then(({ data }) => {
        if (data.code === 20000) {
          this.$message({
            message: '添加分类成功',
            type: 'success'
          })
          this.categoryForm = false
          this.food.category = {
            name: '',
            description: ''
          }
          this.getCategoryList()
        }
      })
    },
    /* 图片上传之前格式大小检查 */
    beforeUpload (file) {
      const isImage = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isImage) {
        this.$message.error('文件格式不正确')
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('图片大小不能超过2M')
      }
      return isImage && isLt2M
    },
    /* 上传成功后的回调函数 */
    uploadSuccess (data) {
      if (data.code === 20000) {
        this.food.image_path = data.data.realFileName
        this.image = {
          showImage: true,
          src: `${process.env.VUE_APP_BASE_API}file/getImgStream?fileName=${data.data.realFileName}`,
          prevList: [`${process.env.VUE_APP_BASE_API}file/getImgStream?fileName=${data.data.realFileName}`]
        }
      }
    },
    /* 添加规格 */
    saveSpecs () {
      if (this.specs.index >= 0) {
        this.food.specsJson[this.specs.index].specs = this.specs.specs
        this.food.specsJson[this.specs.index].packing_fee = this.specs.packing_fee
        this.food.specsJson[this.specs.index].price = this.specs.price
        this.$message.success('修改规格成功')
      } else {
        this.food.specsJson.push(this.specs)
        this.$message.success('添加规格成功')
      }
      this.visible = false
      this.specs = { ...initSpecs }
      this.title = '添加规格'
    },
    /* 展示要修改的规格数据 */
    showSpecs (scope) {
      this.specs = {
        index: scope.$index,
        specs: scope.row.specs,
        packing_fee: scope.row.packing_fee,
        price: scope.row.price
      }
      this.title = '修改规格'
      this.visible = true
    },
    /* 删除规格 */
    delSpecs (index) {
      this.$confirm('确定删除该规格吗').then(() => {
        this.food.specsJson.splice(index, 1)
        this.$message.success('删除成功')
      })
    },
    saveFood () {
      this.food.attributesJson = JSON.stringify(this.food.attributesJson)
      this.food.specsJson = JSON.stringify(this.food.specsJson)
      this.food.idMenu = this.food.category_id
      this.food.imagePath = this.food.image_path
      this.$http.post(`shopping/${this.food.id ? 'v2/updatefood' : 'addfood'}`, this.food).then(({ data }) => {
        if (data.code === 20000) {
          this.$alert(`${this.food.id ? '修改' : '添加'}成功`, { type: 'success' }).then(() => {
            this.food = { ...initInfo }
            this.specs = { ...initSpecs }
            this.$router.push('shop')
          })
        }
      })
    },
    init () {
      this.food.idShop = this.$route.params.restaurant_id
      if (this.$route.params.item_id) {
        const showFood = this.$route.params
        this.food.name = showFood.name
        this.food.descript = showFood.description
        this.food.category_id = showFood.category_id
        this.food.image_path = showFood.image_path
        this.food.specsJson = showFood.specfoods.map(item => {
          return {
            specs: item.name,
            packing_fee: item.packing_fee,
            price: item.price
          }
        })
        this.food.id = showFood.item_id
        this.image.showImage = true
        this.image.src = process.env.VUE_APP_BASE_API + 'file/getImgStream?fileName=' + this.food.image_path
        this.image.prevList = [this.image.src]
      }
    }
  },
  created () {
    this.init()
    this.uploadHeader.Authorization = this.$cookies.get('token')
    this.getCategoryList()
  }
}
</script>

<style scoped>

</style>
